package com.web.action.webs;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.imageio.ImageIO;

import org.common.util.TranslateHelper;
import org.wface.web.core.ActionSupport;

import com.util.VerifyCode;


import com.manager.model.SysAdmin;
import com.manager.service.file.FileService;
import com.manager.service.news.CategoryService;
import com.manager.service.system.AdminService;
import com.manager.service.user.UserService;
import com.web.model.Category;
import com.web.model.File;
import com.web.model.News;
import com.web.model.Userinfo;
import com.web.service.NewsService;
import com.web.tag.bean.PageModel;

public class WebAction extends ActionSupport {

	private String page;
	private String username;
	private String password;
	private String password1;
	private String true_name;
	private String email;
	private String question;
	private String answer;
	private String code;
	
	
	/**
	 * login页面登陆请求。
	 * 
	 * @return
	 */
	public String login() {
		System.out.println(username + "---" + password);
		UserService uservice = new UserService();
		Userinfo user = uservice.getLoginUser(username,password);
		if (user != null) {
			getRequest().getSession().setAttribute("user", user);
			getRequest().getSession().setAttribute("user_username", user.getUsername());
			return "index";
		} else {
			getRequest().setAttribute("loginMsg", "输入ID或密码不正确!");
			return "login";
		}
	}
	
	

	public String menu() {

		CategoryService cateService = new CategoryService();
		List<Category> categorys = cateService.findShow();
		getRequest().setAttribute("categorys", categorys);
		return "menuList";
	}

	public String category() {
		
	

		String m1 = this.getRequest().getParameter("m1");
		String m2 = this.getRequest().getParameter("m2");
		String m3 = this.getRequest().getParameter("m3");
		String m4 = this.getRequest().getParameter("m4");
		String r = this.getRequest().getParameter("r");
		int tempM = 0;

		CategoryService cateService = new CategoryService();
		List<Category> categorys = cateService.findShow();
	 
		getRequest().getSession().getServletContext().setAttribute("categorys", categorys);
		
		// 四级栏目处理
		Category categoryM1 = new Category();
		Category categoryM2 = new Category();
		Category categoryM3 = new Category();
		Category categoryM4 = new Category();
		// 左侧栏目标题
		String leftTitle = "";
		// 中间栏目标题
		String title = "";
		// 中间背景图
		String bgUrl = "";
		// 栏目类型 0 表示文章 1表示附件
		int type = 0;
		// 拼接四级栏目地址
		String url = "";
		
		String show="";

		if (m1 != null) {
			categoryM1 = cateService.getById(TranslateHelper.parseInteger(m1));
			if (categoryM1 != null && categoryM1.getName() != null && !categoryM1.equals("")) {
				title = categoryM1.getName();
				leftTitle = categoryM1.getName();
				bgUrl = categoryM1.getBgurl();
				tempM = categoryM1.getId();
				url = url + "&m1=" + tempM;
				type = categoryM1.getTypes();
				if(categoryM1.getUrl()!=null&&!categoryM1.getUrl().equals(""))
				show=categoryM1.getUrl();
			}

		}
		if (m2 != null) {
			categoryM2 = cateService.getById(TranslateHelper.parseInteger(m2));
			if (categoryM2 != null && categoryM2.getName() != null && !categoryM2.equals("")) {
				title = categoryM2.getName();
				tempM = categoryM2.getId();
				url = url + "&m2=" + tempM;
				type = categoryM2.getTypes(); 
				show=categoryM2.getUrl();
			}

		}

		if (m3 != null) {
			categoryM3 = cateService.getById(TranslateHelper.parseInteger(m3));
			if (categoryM3 != null && categoryM3.getName() != null && !categoryM3.equals("")) {
				title = categoryM3.getName();
				tempM = categoryM3.getId();
				url = url + "&m3=" + tempM;
				type = categoryM3.getTypes(); 
				show=categoryM3.getUrl();
			}

		}
		if (m4 != null) {
			categoryM4 = cateService.getById(TranslateHelper.parseInteger(m4));
			if (categoryM4 != null && categoryM4.getName() != null && !categoryM4.equals("")) {
				title = categoryM4.getName();
				tempM = categoryM4.getId();
				url = url + "&m4=" + tempM;
				type = categoryM4.getTypes();
 
				show=categoryM4.getUrl();
			}

		}
       
		getRequest().setAttribute("m1", categoryM1);
		getRequest().setAttribute("m2", categoryM2);
		getRequest().setAttribute("m3", categoryM3);
		getRequest().setAttribute("m4", categoryM4); 
		getRequest().setAttribute("m", tempM);
		getRequest().setAttribute("title", title);
		getRequest().setAttribute("leftTitle", leftTitle);
		getRequest().setAttribute("bgUrl", bgUrl);

		if (tempM > 0) {
			PageModel model = new PageModel();
			int pageNum = TranslateHelper.parseInteger(page);
			model.setPageNum(pageNum);

			if (type == 1) {
				FileService fileService = new FileService();
				List<File> list = fileService.findListByCat(tempM, model);
				getRequest().setAttribute("list", list);
				getRequest().setAttribute(PageModel.PAGEMODEL, model);
				model.setPaths(getBasePath() + "/webs/category.do?" + url);
				getRequest().setAttribute(PageModel.PAGEMODEL, model);
				getRequest().setAttribute("murl", url);
				return "download";
			} else {
				NewsService newsService = new NewsService();
				List<News> list = newsService.listNewsByCat(tempM, model);
				getRequest().setAttribute("list", list);
				// 如果该目录下只有一篇文章
				if (list != null && pageNum == 0 && list.size() == 1) {
					News news = list.get(0);

					StringBuffer content = new StringBuffer();
					content.append("");
					if (news != null && !news.getId().equals("")) {
						Clob clob = news.getContentHtml();
						Reader reader = null;
						try {
							reader = clob.getCharacterStream();

							int i = 0;
							char ac[] = new char[200];
							while ((i = reader.read(ac, 0, 200)) != -1)
								content.append(new String(ac, 0, i));

						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							if (reader != null) {
								try {
									reader.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}
					getRequest().setAttribute("news", news);
					String basePath = getBasePath();
					getRequest().setAttribute("content", content.toString().replaceAll("src=\"upload/", "src=\"" + basePath + "upload/"));
					getRequest().setAttribute("murl", url);
					return "showDetail";

				} else {
					
				 if(tempM==320){
					 return "!"+"/msg/list.do";
				 }
					// 其他情况
				if(r==null&&show!=null&&!show.equals("")){//关联目录 r==null避免重复跳转
					String tempShow=show+"&r=1";
					System.out.println(tempShow);
					
				  return "!"+show+"&r=1";
				 }
					model.setPaths(getBasePath() + "/webs/category.do?" + url);
					getRequest().setAttribute(PageModel.PAGEMODEL, model);
					getRequest().setAttribute("show", show);
					getRequest().setAttribute("murl", url);
				}
			}
		}

		return "category";
	}

	public String detail() {

		String m1 = this.getRequest().getParameter("m1");
		String m2 = this.getRequest().getParameter("m2");
		String m3 = this.getRequest().getParameter("m3");
		String m4 = this.getRequest().getParameter("m4");
		String nid = this.getRequest().getParameter("nid");
		int tempM = 0;

		CategoryService cateService = new CategoryService();
		List<Category> categorys = cateService.findShow(); 
		getRequest().getSession().getServletContext().setAttribute("categorys", categorys);
		

		// 四级栏目处理
		Category categoryM1 = new Category();
		Category categoryM2 = new Category();
		Category categoryM3 = new Category();
		Category categoryM4 = new Category();
		// 左侧栏目标题
		String leftTitle = "";
		// 中间栏目标题
		String title = "";
		// 中间背景图
		String bgUrl = "";
		// 栏目类型 0 表示文章 1表示附件
		int type = 0;
		// 拼接四级栏目地址
		String url = "";

		if (m1 != null) {
			categoryM1 = cateService.getById(TranslateHelper.parseInteger(m1));
			if (categoryM1 != null && categoryM1.getName() != null && !categoryM1.equals("")) {
				title = categoryM1.getName();
				leftTitle = categoryM1.getName();
				bgUrl = categoryM1.getBgurl();
				tempM = categoryM1.getId();
				url = url + "&m1=" + tempM;
				type = categoryM1.getTypes();
			}

		}
		if (m2 != null) {
			categoryM2 = cateService.getById(TranslateHelper.parseInteger(m2));
			if (categoryM2 != null && categoryM2.getName() != null && !categoryM2.equals("")) {
				title = categoryM2.getName();
				tempM = categoryM2.getId();
				url = url + "&m2=" + tempM;
				type = categoryM2.getTypes();
			}

		}

		if (m3 != null) {
			categoryM3 = cateService.getById(TranslateHelper.parseInteger(m3));
			if (categoryM3 != null && categoryM3.getName() != null && !categoryM3.equals("")) {
				title = categoryM3.getName();
				tempM = categoryM3.getId();
				url = url + "&m3=" + tempM;
				type = categoryM3.getTypes();
			}

		}
		if (m4 != null) {
			categoryM4 = cateService.getById(TranslateHelper.parseInteger(m4));
			if (categoryM4 != null && categoryM4.getName() != null && !categoryM4.equals("")) {
				title = categoryM4.getName();
				tempM = categoryM4.getId();
				url = url + "&m4=" + tempM;
				type = categoryM4.getTypes();
			}

		}
		News news = new News();
		NewsService newsService = new NewsService();
		news = newsService.getById(TranslateHelper.parseInteger(nid));
		StringBuffer content = new StringBuffer();
		content.append("");
		if (news != null && !news.getId().equals("")) {
			Clob clob = news.getContentHtml();
			Reader reader = null;
			try {
				reader = clob.getCharacterStream();

				int i = 0;
				char ac[] = new char[200];
				while ((i = reader.read(ac, 0, 200)) != -1)
					content.append(new String(ac, 0, i));

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		String basePath = this.getBasePath();
		String htmlContent= content.toString().replaceAll("value=\"upload/","value=\""+ basePath + "upload/");
		 htmlContent=htmlContent.replaceAll("src=\"upload/", "src=\"" + basePath + "upload/");
		getRequest().setAttribute("content",htmlContent);
		getRequest().setAttribute("news", news);
		getRequest().setAttribute("m1", categoryM1);
		getRequest().setAttribute("m2", categoryM2);
		getRequest().setAttribute("m3", categoryM3);
		getRequest().setAttribute("m4", categoryM4);
		if (m1 == null && m2 == null && m3 == null && m4 == null) {
			List<Category> clist = new ArrayList<Category>();
			int cid = news.getClassid();
			Category cate = cateService.getById(cid);
			clist.add(cate);
			while (cate != null && cate.getPid() > 0) {
				cate = cateService.getById(cate.getPid());
				clist.add(cate);
			}
			Collections.reverse(clist);
			for (int i = 0; i < clist.size(); i++) {
				getRequest().setAttribute("m" + (i + 1), clist.get(i));
			}
		}

		getRequest().setAttribute("title", title);
		getRequest().setAttribute("leftTitle", leftTitle);
		getRequest().setAttribute("bgUrl", bgUrl);

		return "showDetail";
	}
	
	
	/**
	 * 
	 * 验证码请求方法， 通用方法， 可在无filter下调用。
	 * 
	 * @return
	 * @throws IOException
	 */
	public String vc() throws IOException {
		//设置浏览器不缓存本页
		getResponse().setHeader("Cache-Control", "no-cache");

		//生成验证码，写入用户session
		String verifyCode = VerifyCode.generateTextCode(
				VerifyCode.TYPE_ALL_MIXED, 4, null);
		getRequest().getSession().setAttribute("verifyCode", verifyCode);

		//输出验证码给客户端
		getResponse().setContentType("image/jpeg");
		BufferedImage bim = VerifyCode.generateImageCode(verifyCode, 90, 27, 1,
				true, Color.WHITE, Color.BLACK, null);
		ImageIO.write(bim, "JPEG", getResponse().getOutputStream());
		return null;
	}
	
	/**
	 *  register.jsp页面提交按钮
	 * 
	 * @return
	 */
	public String register() {

		// 取session中的正确验证码
		String legalCode = null;
		if (getRequest().getSession().getAttribute("verifyCode") != null)
			legalCode = (String) (getRequest().getSession()
					.getAttribute("verifyCode"));
		if (code == null || !code.equalsIgnoreCase(legalCode)) {
			getRequest().setAttribute("registerMsg", "验证码输入不正确!");
			return "register";
		}
		
		UserService uservice = new UserService();
		if (uservice.getByUserName(username) == null) {
			getRequest().setAttribute("registerMsg", "该用户已存在，请重新输入!");
			return "register";
		}
		
		Userinfo user = new Userinfo();
		user.setUsername(username);
		user.setPassword(password1);
		user.setEmail(email);
		user.setName(true_name);
		user.setPassPro(question);
		user.setPassAns(answer);

		uservice.saveOrUpdate(user);

		return "index";
	}

	
	
	
	
	private String getBasePath() {
		String path = getRequest().getContextPath();
		String serverName = getRequest().getServerName();
		if (path != null && path.equals("/")) {
			path = "";
		}
		String basePath = getRequest().getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort() + path + "/";
		return basePath;
	}
	
	private List<Category> disposeCategory(List<Category> datas,int pid) {
		if (datas == null)
			return null;
		List<Category> categorys = new ArrayList<Category>();
		for (int i = 0; i < datas.size(); i++) {
			Category temp = datas.get(i);
			if (pid==temp.getPid()) {
				categorys.add(temp);
			} else {
				for (int j = 0; j < datas.size(); j++) {
					Category ptemp = datas.get(j);
					if (ptemp.getId().equals(temp.getPid())) {
						List<Category> pcategorys = ptemp.getCategorys();
						if (pcategorys == null)
							pcategorys = new ArrayList<Category>();
						if (!pcategorys.contains(temp))
							pcategorys.add(temp);
						ptemp.setCategorys(pcategorys);
					}
				}
			}
		}
		return categorys;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setTrue_name(String trueName) {
		true_name = trueName;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setQuestion(String question) {
		this.question = question;
	}
	public void setAnswer(String answer) {
		this.answer = answer;
	}
	public void setPassword1(String password1) {
		this.password1 = password1;
	}
	public void setCode(String code) {
		this.code = code;
	}
}
